package com.xbongbong.paas.service.impl;

import com.alibaba.dingtalk.openapi.helper.AuthHelper;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.service.CompanyService;
import com.xbongbong.paas.service.IsvReceiveService;
import com.xbongbong.paas.service.async.IsvReceiveAsync;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.user.pojo.dto.SyncOrganizationDTO;
import com.xbongbong.sys.domain.entity.CompanyEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static com.xbongbong.paas.redis.RedisPrefixConstant.DEPARTMENT_REFRESH_STATUS;

/**
 * 对应IsvReceiveController业务实现
 * @author kaka
 * @version v1.0
 * @date 2019/4/26 13:46
 * @since v1.0
 */
@Service("isvReceiveService")
public class IsvReceiveServiceImpl implements IsvReceiveService {

    private static final Logger LOG = LoggerFactory.getLogger(IsvReceiveServiceImpl.class);

    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private AuthHelper authHelper;
    @Resource
    private IsvReceiveAsync isvReceiveAsync;

    @Resource
    private CompanyService companyService;

    @Override
    public BaseVO syncOrganization(SyncOrganizationDTO syncOrganizationDTO) throws XbbException {
        String updateCorpid = syncOrganizationDTO.getUpdateCorpid();
        final String accessToken;
        try {
            /*
             * {"code":1,"msg":"xxxx"} 1.成功，2，正在同步中 >2 错误信息
             */
            String syncDepUserStatusBefore = paasRedisHelper.getValue(DEPARTMENT_REFRESH_STATUS, updateCorpid);

            if(syncDepUserStatusBefore != null) {
                JSONObject syncDepUserStatusJsonBefore = JSONObject.parseObject(syncDepUserStatusBefore);
                if(syncDepUserStatusJsonBefore != null) {
                    Integer syncCode = syncDepUserStatusJsonBefore.getInteger("code");
                    if(syncCode.equals(2)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100081);
                    }
                }
            }

            /* ==============================防止同步时permanentcode获取失败===================== */
            companyService.getPermanentCode(updateCorpid);
            /* ================================================================================= */

            accessToken = authHelper.getAccessToken(updateCorpid);

            /*
             * 同步组织架构，起线程
             * @Async
             */
            isvReceiveAsync.manualSyncOrgThread(accessToken, updateCorpid);

        } catch (XbbException xe) {
            //业务异常继续往外抛出
            throw xe;
        } catch (Exception e) {
            LOG.error("同步组织架构出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100082);
        }

        return new BaseVO();
    }

    @Override
    public void changeAuth(String accessToken, String corpid, String corpName) {
        isvReceiveAsync.changeAuthThread(accessToken, corpid, corpName);
    }

    @Override
    public void authCompany(String xbbFrom, String accessToken, CompanyEntity company) {
        isvReceiveAsync.authCompanyThread(xbbFrom, accessToken, company);
    }

}
